﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UpdateWizard.Entities;
using UpdateWizard.Utilities;

namespace UpdateWizard.Actions
{
    public class Generate
    {
        public static void Execute()
        {
            List<FileInfo> allFiles = new List<FileInfo>();
            List<UP_FileItem> CurrentVersionFiles = new List<UP_FileItem>();
            string ditectDirName = string.Empty;
            if(string.IsNullOrEmpty(Configs.BaseConfig.TraceDirectory))
            {
                ditectDirName = AppDomain.CurrentDomain.BaseDirectory;
            }
            else
            {
                ditectDirName = Configs.BaseConfig.TraceDirectory;
            }
            FileUtil.FindAllFiles(ditectDirName,ref allFiles);
            string[] extFilters = Configs.BaseConfig.ExtensionFilter.Split(' ');
            //后缀名过滤
            var deleteList = new List<string>();
            //文件名过滤
            List<string> fileFilterList = new List<string>();
            fileFilterList.AddRange(Configs.BaseConfig.FileNameFilter.Select(it => $"{Configs.BaseConfig.TraceDirectory}\\{it}").ToList());
            if (extFilters != null && extFilters.Count() > 0)
            {
                foreach (var file in allFiles)
                { 
                    if(extFilters.Contains(file.Extension))
                    {
                        deleteList.Add(file.FullName);
                    }
                    foreach (var filter in fileFilterList)
                    {
                        if (file.FullName.Contains(filter))
                        {
                            deleteList.Add(file.FullName);
                        }
                    }
                }
            }
            foreach (var delItem in deleteList)
            {
                if(allFiles.Any(it => it.FullName == delItem))
                {
                    allFiles.Remove(allFiles.FirstOrDefault(it => it.FullName == delItem));
                }
            }
            //计算文件摘要
            foreach (var item in allFiles)
            {
                string md5 = FileData.GetMD(item.FullName);
                string relativePath = item.FullName.Replace(Configs.BaseConfig.TraceDirectory,string.Empty);
                int indexOfRel = relativePath.LastIndexOf('\\');
                string absoluteRelativePath = string.Empty;
                if(indexOfRel > 0)
                {
                    absoluteRelativePath = relativePath.Substring(0, indexOfRel);
                }
                int indexOfExt = item.Name.LastIndexOf('.');
                string fileName = string.Empty;
                if (indexOfExt > 0)
                {
                    fileName = item.Name.Substring(0, indexOfExt);
                }
                CurrentVersionFiles.Add(new UP_FileItem
                { 
                    ID = Guid.NewGuid().ToString(),
                    MD = md5,
                    RelativePath = absoluteRelativePath,
                    Extension = item.Extension,
                    FileName = fileName,
                    ModifyTime = item.LastWriteTime,
                    ModifyType = -1
                });
            }

            //提取最近的文件摘要
            var recentSummary = UpdateStrategy.QueryUpdateSummary();

            foreach (var CurrItem in CurrentVersionFiles)
            {
                var correspondItem = recentSummary.FirstOrDefault(it => it.RelativePath == CurrItem.RelativePath
                                                            && it.FileName == CurrItem.FileName
                                                            && it.Extension == CurrItem.Extension);
                if(correspondItem == null)
                {
                    //新增的文件
                    CurrItem.ModifyType = (short)ModifyTypeEnum.ADD;
                }
                else if(correspondItem.MD == CurrItem.MD)
                {
                    //未改动
                    CurrItem.ModifyType = (short)ModifyTypeEnum.NOM;
                }
                else if(correspondItem.MD != CurrItem.MD)
                {
                    //修改
                    CurrItem.ModifyType = (short)ModifyTypeEnum.MDF;
                }
            }

            //主动删除文件
            if (Configs.BaseConfig.DeleteItems != null && Configs.BaseConfig.DeleteItems.Count > 0)
            {
                foreach (var deleteItem in Configs.BaseConfig.DeleteItems)
                {
                    var Item = recentSummary.FirstOrDefault(it => $"{it.RelativePath}{it.FileName}.{it.Extension}" == deleteItem);
                    if (Item != null)
                    {
                        Item.ModifyType = (short)ModifyTypeEnum.DEL;
                        if (CurrentVersionFiles.Any(it => $"{it.RelativePath}{it.FileName}.{it.Extension}" == $"{Item.RelativePath}{Item.FileName}{Item.Extension}"))
                        {
                            CurrentVersionFiles.Single(it => $"{it.RelativePath}{it.FileName}.{it.Extension}" == $"{Item.RelativePath}{Item.FileName}{Item.Extension}").ModifyType = (short)ModifyTypeEnum.DEL;
                        }
                        //else
                        //{
                        //    CurrentVersionFiles.Add(new UP_FileItem
                        //    {
                        //        ID = Guid.NewGuid().ToString(),
                        //        FileName = Item.FileName,
                        //        RelativePath = Item.RelativePath,
                        //        Extension = Item.Extension,
                        //        MD = 
                        //    });
                        //}
                    }
                } 
            }

            var mds = CurrentVersionFiles.Where(it => it.ModifyType == (short)ModifyTypeEnum.NOM).Select(it => it.MD).ToList();
            foreach(var item in mds)
            {
                var target = CurrentVersionFiles.FirstOrDefault(it => it.MD == item);
                CurrentVersionFiles.Remove(target);
            }

            string result = JsonConvert.SerializeObject(CurrentVersionFiles);
            string targetPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "versionPatch.json");
            File.WriteAllText(targetPath, result);
        }
    }
}
